package org.example.shoppingsystem.service;

import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.example.shoppingsystem.dao.ProductMapper;
import org.example.shoppingsystem.model.Product;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.io.Resources;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class ProductServiceImpl implements ProductService {
    private SqlSessionFactory sqlSessionFactory;

    public ProductServiceImpl() {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Product> findAllProducts() {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            ProductMapper mapper = session.getMapper(ProductMapper.class);
            return mapper.findAllProducts();
        }
    }

    @Override
    public boolean addProduct(Product product) {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            ProductMapper mapper = session.getMapper(ProductMapper.class);
            int rows = mapper.addProduct(product);
            session.commit();
            return rows>0;
        }
    }

    @Override
    public boolean isProductNameExists(String name) {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            ProductMapper mapper = session.getMapper(ProductMapper.class);
            int count = mapper.isProductNameExists(name);
            return count > 0;
        }
    }
}